<template>
  <div class="field-matcher">
    <!-- 接口选择区域 -->
    <div class="api-selection" v-if="!selectedApi">
      <a-button type="primary" @click="showApiModal = true">
        选择接口
      </a-button>
      <span style="margin-left: 12px; color: #999;">
        请先选择接口，系统将自动根据接口出参进行字段匹配
      </span>
    </div>

    <!-- 已选择的接口信息 -->
    <div v-if="selectedApi" class="selected-api-info">
      <span class="method" :class="selectedApi.method.toLowerCase()">
        {{ selectedApi.method }}
      </span>
      <span class="api-path">{{ selectedApi.path }}</span>
      <span class="api-summary">{{ selectedApi.summary }}</span>
      <a-button type="link" size="small" @click="showApiModal = true">
        重新选择
      </a-button>
      <a-button type="link" size="small" @click="clearApi" danger>
        清空
      </a-button>
    </div>

    <!-- 自动匹配结果展示 -->
    <div v-if="selectedApi && autoMatchedFields.length > 0" class="auto-match-result">
      <a-alert
        :message="`已自动匹配 ${autoMatchedFields.length} 个字段`"
        type="success"
        show-icon
        style="margin-bottom: 16px;"
      />
    </div>

    <!-- 字段匹配表格 - 按类型分组展示 -->
    <div v-if="selectedApi" class="field-groups">
      <!-- 快速筛选按钮 -->
      <div style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center;">
        <span>快速筛选：</span>
        <a-radio-group v-model:value="fieldFilter" size="small">
          <a-radio value="all">全部 ({{ getFilterStats().total }})</a-radio>
          <a-radio value="unmatched-lowmatched">未匹配&低匹配 ({{ getFilterStats().unmatched + getFilterStats().lowmatched }})</a-radio>
        </a-radio-group>
      </div>
      
      <a-tabs type="card">
        <!-- 查询条件字段 -->
        <a-tab-pane 
          v-if="dataSource.search.length > 0" 
          key="search"
          :tab="`查询条件 (${searchFieldStats.matched}/${searchFieldStats.total})`"
        >
          <div class="field-group">
            <a-table 
              :columns="columns" 
              :data-source="filterFields(dataSource.search)" 
              :pagination="false" 
              rowKey="label"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'selection'">
                  <a-checkbox
                    :checked="selectedRowKeys.search.includes(record.label)"
                    @change="(e) => {
                      if (e.target.checked) {
                        if (!selectedRowKeys.search.includes(record.label)) {
                          selectedRowKeys.search.push(record.label);
                        }
                      } else {
                        const index = selectedRowKeys.search.indexOf(record.label);
                        if (index > -1) {
                          selectedRowKeys.search.splice(index, 1);
                        }
                      }
                    }"
                  />
                </template>
                <template v-if="column.key === 'componentType'">
                  <a-select
                    v-model:value="record.componentType"
                    style="width: 100px"
                    placeholder="选择组件类型"
                    size="small"
                  >
                    <a-select-option 
                      v-for="option in componentTypeOptions" 
                      :key="option.value"
                      :value="option.value"
                      :title="option.label"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="column.key === 'required'">
                  <a-tag :color="record.required ? 'red' : 'green'">
                    {{ record.required ? '必填' : '非必填' }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'swaggerField'">
                  <a-auto-complete
                    v-model:value="record.swaggerField"
                    style="width: 240px"
                    placeholder="请输入或选择Swagger字段"
                    @select="(value) => handleAutoCompleteSelect(record, value)"
                    allow-clear
                    :options="filterAutoCompleteOptions(record._searchText || '')"
                    @search="(value) => record._searchText = value"
                  >
                  </a-auto-complete>
                </template>
                <template v-if="column.key === 'matchStatus'">
                  <a-tag :color="getMatchStatusColor(record)">
                    {{ getMatchStatusText(record) }}
                  </a-tag>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 列表字段 -->
        <a-tab-pane 
          v-if="dataSource.table.length > 0" 
          key="table"
          :tab="`列表字段 (${tableFieldStats.matched}/${tableFieldStats.total})`"
        >
          <div class="field-group">
            <a-table 
              :columns="columns" 
              :data-source="filterFields(dataSource.table)" 
              :pagination="false" 
              rowKey="label"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'selection'">
                  <a-checkbox
                    :checked="selectedRowKeys.table.includes(record.label)"
                    @change="(e) => {
                      if (e.target.checked) {
                        if (!selectedRowKeys.table.includes(record.label)) {
                          selectedRowKeys.table.push(record.label);
                        }
                      } else {
                        const index = selectedRowKeys.table.indexOf(record.label);
                        if (index > -1) {
                          selectedRowKeys.table.splice(index, 1);
                        }
                      }
                    }"
                  />
                </template>
                <template v-if="column.key === 'componentType'">
                  <a-select
                    v-model:value="record.componentType"
                    style="width: 100px"
                    placeholder="选择组件类型"
                    size="small"
                  >
                    <a-select-option 
                      v-for="option in componentTypeOptions" 
                      :key="option.value"
                      :value="option.value"
                      :title="option.label"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="column.key === 'required'">
                  <a-tag :color="record.required ? 'red' : 'green'">
                    {{ record.required ? '必填' : '非必填' }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'swaggerField'">
                  <a-auto-complete
                    v-model:value="record.swaggerField"
                    style="width: 240px"
                    placeholder="请输入或选择Swagger字段"
                    @select="(value) => handleAutoCompleteSelect(record, value)"
                    allow-clear
                    :options="filterAutoCompleteOptions(record._searchText || '')"
                    @search="(value) => record._searchText = value"
                  >
                  </a-auto-complete>
                </template>
                <template v-if="column.key === 'matchStatus'">
                  <a-tag :color="getMatchStatusColor(record)">
                    {{ getMatchStatusText(record) }}
                  </a-tag>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 表单字段 -->
        <a-tab-pane 
          v-if="dataSource.form.length > 0" 
          key="form"
          :tab="`表单字段 (${formFieldStats.matched}/${formFieldStats.total})`"
        >
          <div class="field-group">
            <a-table 
              :columns="columns" 
              :data-source="filterFields(dataSource.form)" 
              :pagination="false" 
              rowKey="label"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'selection'">
                  <a-checkbox
                    :checked="selectedRowKeys.form.includes(record.label)"
                    @change="(e) => {
                      if (e.target.checked) {
                        if (!selectedRowKeys.form.includes(record.label)) {
                          selectedRowKeys.form.push(record.label);
                        }
                      } else {
                        const index = selectedRowKeys.form.indexOf(record.label);
                        if (index > -1) {
                          selectedRowKeys.form.splice(index, 1);
                        }
                      }
                    }"
                  />
                </template>
                <template v-if="column.key === 'componentType'">
                  <a-select
                    v-model:value="record.componentType"
                    style="width: 100px"
                    placeholder="选择组件类型"
                    size="small"
                  >
                    <a-select-option 
                      v-for="option in componentTypeOptions" 
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-if="column.key === 'required'">
                  <a-tag :color="record.required ? 'red' : 'green'">
                    {{ record.required ? '必填' : '非必填' }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'swaggerField'">
                  <a-auto-complete
                    v-model:value="record.swaggerField"
                    style="width: 240px"
                    placeholder="请输入或选择Swagger字段"
                    @select="(value) => handleAutoCompleteSelect(record, value)"
                    allow-clear
                    :options="filterAutoCompleteOptions(record._searchText || '')"
                    @search="(value) => record._searchText = value"
                  >
                  </a-auto-complete>
                </template>
                <template v-if="column.key === 'matchStatus'">
                  <a-tag :color="getMatchStatusColor(record)">
                    {{ getMatchStatusText(record) }}
                  </a-tag>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 接口选择弹窗 -->
    <a-modal
      v-model:open="showApiModal"
      title="选择接口"
      width="800px"
      :footer="null"
    >
      <div class="api-modal-content">
        <!-- 搜索表单 -->
        <div class="search-box">
          <a-input-search 
            v-model:value.trim="apiSearchTerm" 
            placeholder="搜索API..." 
            style="margin-bottom: 16px" 
            @search="handleSearch"
          />
        </div>

        <!-- API列表 -->
        <div class="api-list-container">
          <a-collapse v-if="groupedApis.length > 0" v-model:activeKey="activeKeys" ghost>
            <template v-for="group in groupedApis" :key="group.tag">
              <a-collapse-panel :header="`${group.tag} (${group.apis.length})`">
                <a-list
                  :data-source="group.apis"
                  :loading="loading"
                  item-layout="horizontal"
                >
                  <template #renderItem="{ item }">
                    <a-list-item 
                      :class="['api-item', { active: selectedApi && selectedApi.path === item.path }]"
                      @click="selectApi(item)"
                    >
                      <a-list-item-meta>
                        <template #title>
                          <span class="path">{{ item.path }}</span>
                        </template>
                        <template #description>
                          <span class="method" :class="item.method">{{ item.method.toUpperCase() }}</span>
                          <span class="summary">{{ item.summary }}</span>
                        </template>
                      </a-list-item-meta>
                    </a-list-item>
                  </template>
                </a-list>
              </a-collapse-panel>
            </template>
          </a-collapse>
          <div v-else>
            <a-list
              :data-source="filteredApis"
              :loading="loading"
              item-layout="horizontal"
            >
              <template #renderItem="{ item }">
                <a-list-item 
                  :class="['api-item', { active: selectedApi && selectedApi.path === item.path }]"
                  @click="selectApi(item)"
                >
                  <a-list-item-meta>
                    <template #title>
                      <span class="path">{{ item.path }}</span>
                    </template>
                    <template #description>
                      <span class="method" :class="item.method">{{ item.method.toUpperCase() }}</span>
                      <span class="summary">{{ item.summary }}</span>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
              <template #footer>
                <div v-if="filteredApis.length === 0" class="no-data">
                  <a-empty description="暂无匹配的API" />
                </div>
              </template>
            </a-list>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, inject, nextTick, onMounted , watch} from 'vue';
import { SwaggerUtils } from '../swaggerUtils.js'

const props = defineProps({
  fields: {
    type: Array,
    required: true
  },
  areaName: {
    type: String,
    required: true
  },
  dataSource: {
    type: Object,
    default: () => ({ search: [], table: [], form: [] })
  }
});

// 获取全局API状态
const apiState = inject('apiState')

const emit = defineEmits(['field-matched']);

// 状态变量
const showApiModal = ref(false);
const selectedApi = ref(null);
const apiSearchTerm = ref('')
const activeKeys = ref([])
const autoMatchedFields = ref([]);
const selectedRowKeys = ref({ search: [], table: [], form: [] });// 状态变量
const fieldFilter = ref('unmatched-lowmatched'); // 'all' or 'unmatched-lowmatched'

// 初始化选中所有行
const initializeAllSelected = () => {
  if (props.dataSource.search && props.dataSource.search.length > 0) {
    selectedRowKeys.value.search = props.dataSource.search.map(field => field.label);
  }
  if (props.dataSource.table && props.dataSource.table.length > 0) {
    selectedRowKeys.value.table = props.dataSource.table.map(field => field.label);
  }
  if (props.dataSource.form && props.dataSource.form.length > 0) {
    selectedRowKeys.value.form = props.dataSource.form.map(field => field.label);
  }
};

// 监听数据源变化，初始化选中状态
watch(() => props.fields, (newFields) => {
  if (newFields && newFields.length > 0) {
    initializeAllSelected();
  }
}, { immediate: true });

// 组件挂载时初始化
onMounted(() => {
  initializeAllSelected();
});

// 组件类型选项
const componentTypeOptions = [
  { label: 'Input', value: 'Input' },
  { label: 'Select', value: 'Select' },
  { label: 'DatePicker', value: 'DatePicker' },
];

const columns = [
  {
    title: '选择',
    key: 'selection',
    width: 50,
    customCell: () => {
      return {
        props: {
          colSpan: 0,
          rowSpan: 0
        }
      };
    }
  },
  {
    title: '需求字段',
    dataIndex: 'label',
    key: 'label',
    width: 150
  },
  {
    title: '组件类型',
    dataIndex: 'componentType',
    key: 'componentType',
    width: 120
  },
  {
    title: '必填',
    dataIndex: 'required',
    key: 'required',
    width: 60
  },
  {
    title: 'Swagger字段',
    dataIndex: 'swaggerField',
    key: 'swaggerField',
    width: 220
  },
  {
    title: '匹配状态',
    dataIndex: 'matchStatus',
    key: 'matchStatus',
    width: 80
  }
];

// 处理字段选择
const handleFieldSelect = (record, value, similarity) => {
  record.swaggerField = value;
  record.similarity = similarity;
};

// 处理自动完成字段选择
const handleAutoCompleteSelect = (record, value) => {
  if (value) {
    record.swaggerField = value;
    record.similarity = 1; // 手动选择的相似度设为1
    console.log(`手动选择字段: "${record.label}" -> "${value}"`);
  }
};

// 自动完成搜索过滤
const filterAutoCompleteOptions = (inputValue) => {
  if (!inputValue || !outputFields.value.length) {
    return outputFields.value.map(field => ({
      value: field.fieldKey,
      label: `${field.fieldKey} - ${field.label}`
    }));
  }
  
  const searchText = inputValue.toLowerCase().trim();
  return outputFields.value
    .filter(field => {
      const fieldKey = field.fieldKey.toLowerCase();
      const label = (field.label || '').toLowerCase();
      const displayText = `${fieldKey} - ${label}`;
      
      // 支持多种匹配方式
      return fieldKey.includes(searchText) || 
             label.includes(searchText) || 
             displayText.includes(searchText);
    })
    .map(field => ({
      value: field.fieldKey,
      label: `${field.fieldKey} - ${field.label}`
    }));
};

// 获取匹配状态颜色
const getMatchStatusColor = (record) => {
  if (!record.swaggerField) return 'default';
  if (record.similarity > 0.8) return 'success';
  if (record.similarity > 0.5) return 'warning';
  return 'error';
};

// 获取匹配状态文本
const getMatchStatusText = (record) => {
  if (!record.swaggerField) return '未匹配';
  if (record.similarity > 0.8) return '高匹配';
  if (record.similarity > 0.5) return '中匹配';
  return '低匹配';
};

// 提取字段名（移除中文描述，保留英文字段名）
const extractFieldName = (text) => {
  // 移除括号及其中内容
  text = text.replace(/\([^)]*\)/g, '');
  // 移除常用前缀后缀
  text = text.replace(/(查询|条件|字段|名称|编码|编号|代码)/g, '');
  // 提取英文部分
  const englishMatch = text.match(/[a-zA-Z_][a-zA-Z0-9_]*/);
  return englishMatch ? englishMatch[0].toLowerCase() : text.toLowerCase();
};

// 计算相似度
const calculateSimilarity = (str1, str2) => {
  if (!str1 || !str2) return 0;
  
  // 完全匹配
  if (str1 === str2) return 1;
  
  // 包含匹配
  if (str1.includes(str2) || str2.includes(str1)) return 0.9;
  
  // 编辑距离相似度
  const distance = levenshteinDistance(str1, str2);
  const maxLength = Math.max(str1.length, str2.length);
  return 1 - (distance / maxLength);
};

// 计算置信度
const calculateConfidence = (label, swaggerField) => {
  const labelName = extractFieldName(label);
  const fieldName = extractFieldName(swaggerField);
  return calculateSimilarity(labelName, fieldName);
};

// 编辑距离算法
const levenshteinDistance = (str1, str2) => {
  const matrix = [];
  
  for (let i = 0; i <= str2.length; i++) {
    matrix[i] = [i];
  }
  
  for (let j = 0; j <= str1.length; j++) {
    matrix[0][j] = j;
  }
  
  for (let i = 1; i <= str2.length; i++) {
    for (let j = 1; j <= str1.length; j++) {
      if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        matrix[i][j] = Math.min(
          matrix[i - 1][j - 1] + 1,
          matrix[i][j - 1] + 1,
          matrix[i - 1][j] + 1
        );
      }
    }
  }
  
  return matrix[str2.length][str1.length];
};

// 过滤API列表
const filteredApis = computed(() => {
  if (!apiState.data) return [];
  
  const allApis = Object.entries(apiState.data.paths).flatMap(([path, methods]) => 
    Object.entries(methods).map(([method, details]) => ({
      path,
      method,
      summary: details.summary || details.description || '',
      tags: details.tags ? details.tags.join(', ') : '未分类'
    }))
  )
  
  if (!apiSearchTerm.value) return allApis
  
  const term = apiSearchTerm.value.toLowerCase()
  return allApis.filter(api =>
    api.path.toLowerCase().includes(term) ||
    api.summary.toLowerCase().includes(term) ||
    api.tags.toLowerCase().includes(term)
  )
})


// 按标签分组的API列表
const groupedApis = computed(() => {
  if (apiSearchTerm.value) {
    // 搜索模式下不分组
    return []
  }
  
  const groups = {}
  filteredApis.value.forEach(api => {
    const tag = api.tags || '未分类'
    if (!groups[tag]) {
      groups[tag] = {
        tag,
        apis: []
      }
    }
    groups[tag].apis.push(api)
  })
  
  // 转换为数组并排序
  return Object.values(groups).sort((a, b) => a.tag.localeCompare(b.tag))
})

// 计算各字段组的匹配统计
const searchFieldStats = computed(() => {
  const fields = props.dataSource.search || []
  const matched = fields.filter(field => field.swaggerField).length
  return { total: fields.length, matched, unmatched: fields.length - matched }
})

const tableFieldStats = computed(() => {
  const fields = props.dataSource.table || []
  const matched = fields.filter(field => field.swaggerField).length
  return { total: fields.length, matched, unmatched: fields.length - matched }
})

const formFieldStats = computed(() => {
  const fields = props.dataSource.form || []
  const matched = fields.filter(field => field.swaggerField).length
  return { total: fields.length, matched, unmatched: fields.length - matched }
})

// 搜索处理
const handleSearch = () => {
  // 过滤逻辑已在computed中处理
};

// 选择API
const selectApi = async (api) => {
  selectedApi.value = api;
  extractParameters(api)
  showApiModal.value = false;
  
  // 等待DOM更新后执行自动匹配
  await nextTick();
  performAutoMatch();
};

// 清空API选择
const clearApi = () => {
  selectedApi.value = null;
  autoMatchedFields.value = [];
  
  // 清空所有字段的匹配
  props.fields.forEach(field => {
    field.swaggerField = null;
  });
};

const outputFields = ref([])
function extractParameters(api) {
  if (!apiState.data || !apiState.data.paths[api.path]) return
  const pathData = apiState.data.paths[api.path]
  const method = pathData[api.method]
  const swaggerOutputParams = SwaggerUtils.extractOutputParams(method, apiState.data)
  const outParams = swaggerOutputParams.properties.data.properties
  // 使用SwaggerUtils提取入参和出参
  outputFields.value = Object.keys(outParams).map(item => {
    return{ fieldKey: item, label: outParams[item].title || outParams[item].description}}
  )
}
// 执行自动匹配
const performAutoMatch = () => {
  if (!selectedApi.value || !outputFields.value.length || !props.fields.length) {
    return;
  }
  
  autoMatchedFields.value = [];
  
  // 日期固定规则匹配映射
  const dateFixedRules = {
    '创建日期': 'createTime',
    '提交日期': 'submitTime',
    '审核日期': 'approvalTime',
    '最后修改日期': 'updateTime'
  };
  
  // 用户相关字段固定规则匹配映射
  const userFixedRules = {
    '创建人': {
      search: 'createUserId',    // 查询条件字段
      table: 'createUserName',   // 列表字段
      form: 'createUserId'       // 表单字段
    },
    '提交人': {
      search: 'submitUserId',
      table: 'submitUserName',
      form: 'submitUserId'
    },
    '审核人': {
      search: 'approvalUserId',
      table: 'approvalUserName',
      form: 'approvalUserId'
    },
    '最后修改人': {
      search: 'updateUserId',
      table: 'updateUserName',
      form: 'updateUserId'
    }
  };
  
  props.fields.forEach(targetField => {
    // 提取目标字段的标签或名称
    const targetLabel = (targetField.label || targetField.name || '').toLowerCase().trim();
    
    if (!targetLabel) {
      return; // 跳过没有标签的字段
    }
    
    // 首先尝试固定规则匹配
    let matchedField = null;
    let similarity = 0;
    
    // 检查日期固定规则匹配
    for (const [ruleLabel, targetFieldKey] of Object.entries(dateFixedRules)) {
      if (targetLabel === ruleLabel.toLowerCase()) {
        // 在outputFields中查找对应的字段
        const foundField = outputFields.value.find(field => field.fieldKey === targetFieldKey);
        if (foundField) {
          matchedField = foundField;
          similarity = 1; // 固定规则匹配的相似度为1
          console.log(`日期固定规则匹配: "${targetLabel}" -> "${targetFieldKey}" (相似度: 100%)`);
          break;
        }
      }
    }
    
    // 如果没有日期规则匹配，检查用户相关字段固定规则
    if (!matchedField) {
      for (const [ruleLabel, fieldMappings] of Object.entries(userFixedRules)) {
        if (targetLabel === ruleLabel.toLowerCase()) {
          // 确定当前字段类型（search/table/form）
          let targetFieldKey = null;
          
          if (props.dataSource.search && props.dataSource.search.includes(targetField)) {
            targetFieldKey = fieldMappings.search;
          } else if (props.dataSource.table && props.dataSource.table.includes(targetField)) {
            targetFieldKey = fieldMappings.table;
          } else if (props.dataSource.form && props.dataSource.form.includes(targetField)) {
            targetFieldKey = fieldMappings.form;
          }
          
          if (targetFieldKey) {
            // 在outputFields中查找对应的字段
            const foundField = outputFields.value.find(field => field.fieldKey === targetFieldKey);
            if (foundField) {
              matchedField = foundField;
              similarity = 1; // 固定规则匹配的相似度为1
              console.log(`用户字段固定规则匹配: "${targetLabel}" -> "${targetFieldKey}" (相似度: 100%)`);
              break;
            }
          }
        }
      }
    }
    
    // 如果没有固定规则匹配，则使用相似度匹配
    if (!matchedField) {
      // 计算所有输出字段的相似度分数
      const similarityScores = outputFields.value.map(sourceField => {
        const sourceLabel = (sourceField.label || sourceField.fieldKey || '').toLowerCase().trim();
        const sim = calculateSimilarity(targetLabel, sourceLabel);
        
        return {
          field: sourceField,
          similarity: sim,
          targetLabel: targetLabel,
          sourceLabel: sourceLabel
        };
      });
      
      // 按相似度降序排序
      similarityScores.sort((a, b) => b.similarity - a.similarity);
      
      // 选择相似度最高的字段（相似度大于0.3才认为有效匹配）
      const bestMatch = similarityScores[0];
      
      if (bestMatch && bestMatch.similarity > 0.3) {
        matchedField = bestMatch.field;
        similarity = bestMatch.similarity;
        console.log(`相似度匹配: "${targetLabel}" -> "${matchedField.fieldKey}" (相似度: ${(similarity * 100).toFixed(1)}%)`);
      }
    }
    
    // 如果有匹配结果，更新字段匹配
    if (matchedField) {
      // 更新字段匹配
      targetField.swaggerField = matchedField.fieldKey;
      autoMatchedFields.value.push({
        targetField: targetField,
        sourceField: matchedField,
        similarity: similarity
      });
      
      // 触发字段匹配事件
      handleFieldSelect(targetField, matchedField.fieldKey, similarity);
    }
  });
  
  console.log(`自动匹配完成: 成功匹配 ${autoMatchedFields.value.length}/${props.fields.length} 个字段`);
};

// 筛选Swagger字段
const filterSwaggerField = (input, option) => {
  const searchText = input.toLowerCase();
  // option 的 fieldKey 和 label 进行匹配
  const fieldKey = option.key.toLowerCase();
  const label = option.label.toLowerCase();
  return fieldKey.includes(searchText) || label.includes(searchText);
};

// 筛选字段函数
const filterFields = (fields) => {
  if (!fields || !Array.isArray(fields)) return [];
  
  // 如果选择了"全部"，显示所有字段
  if (fieldFilter.value === 'all') {
    return fields;
  }
  
  // 如果选择了"未匹配&低匹配"，显示未匹配和低匹配的字段
  if (fieldFilter.value === 'unmatched-lowmatched') {
    return fields.filter(field => {
      // 未匹配：没有swaggerField
      const isUnmatched = !field.swaggerField;
      // 低匹配：有swaggerField但相似度<=0.5
      const isLowMatched = !field.similarity || field.similarity <= 0.5;
      
      return isUnmatched || isLowMatched;
    });
  }
  
  // 默认返回所有字段
  return fields;
};

// 设置筛选器（现在使用radio，逻辑简化）
const setFieldFilter = (filter) => {
  fieldFilter.value = filter;
};

// 获取筛选器标签
const getFilterLabel = () => {
  if (fieldFilter.value === 'all') return '全部';
  if (fieldFilter.value === 'unmatched-lowmatched') return '未匹配&低匹配';
  return '全部';
};

// 获取筛选统计信息
const getFilterStats = () => {
  const allFields = [
    ...(props.dataSource.search || []),
    ...(props.dataSource.table || []),
    ...(props.dataSource.form || [])
  ];
  
  const unmatched = allFields.filter(field => !field.swaggerField).length;
  const lowmatched = allFields.filter(field => {
    if (!field.swaggerField) return false;
    return field.similarity <= 0.5;
  }).length;
  
  return {
    total: allFields.length,
    unmatched: unmatched,
    lowmatched: lowmatched
  };
};

// 提供方法给外部使用，返回字段匹配表格中勾选的字段
const getCheckedFields = () => {
  return {
    search: props.dataSource.search.filter(field => selectedRowKeys.value.search.includes(field.label)).map(item => ({
      fieldKey: item.swaggerField,
      fieldName: item.swaggerField,
      description: item.label,
      componentType: item.componentType
    })),
    table: props.dataSource.table.filter(field => selectedRowKeys.value.table.includes(field.label)).map(item => ({
      fieldKey: item.swaggerField,
      fieldName: item.swaggerField,
      description: item.label,
      componentType: item.componentType
    })),
    form: props.dataSource.form.filter(field => selectedRowKeys.value.form.includes(field.label)).map(item => ({
      fieldKey: item.swaggerField,
      fieldName: item.swaggerField,
      description: item.label,
      componentType: item.componentType
    })),
  };
};

// 暴露方法给父组件使用
defineExpose({
  getCheckedFields
});

</script>

<style scoped>
.field-matcher {
  padding: 10px 0;
}

.api-selection {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 6px;
}

.selected-api-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: #f0f2ff;
  border-radius: 6px;
  border: 1px solid #d6e4ff;
  margin-bottom: 16px;
}

.method {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
}

.method.get {
  background-color: #e6f7ff;
  color: white;
  border: 1px solid #91d5ff;
}

.method.post {
  background-color: #ffa50014;
  color: white;
  border: 1px solid #ffa500;
}

.method.put {
  background-color: #fffbe6;
  color: white;
  border: 1px solid #ffe58f;
}

.method.delete {
  background-color: #fff2f0;
  color: white;
  border: 1px solid #ffccc7;
}

.api-path {
  font-family: monospace;
  font-weight: 500;
}

.api-summary {
  color: #666;
  font-size: 14px;
}

.auto-match-result {
  margin-bottom: 16px;
}

.api-modal-content {
  padding: 16px 0;
}

.api-list-container .ant-list-item {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.api-list-container .ant-list-item:hover {
  border-color: #1890ff;
  background-color: #f6ffed;
}

.api-list-container .ant-list-item.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}

.search-box {
  padding: 0 16px;
}

.api-list-container {
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
}

.api-item {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}

.api-item:hover {
  background-color: #f5f5f5;
}

.api-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.method {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
  text-transform: uppercase;
}

.method.get {
  background: linear-gradient(135deg, #28a745, #218838);
}

.method.post {
  background: linear-gradient(135deg, #ffa500, #ff8c00);
}

.method.put {
  background: linear-gradient(135deg, #007bff, #0069d9);
}

.method.delete {
  background: linear-gradient(135deg, #dc3545, #c82333);
}

.path {
  font-weight: 500;
}

.summary {
  font-size: 12px;
  color: #666;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

/* 滚动条样式优化 */
.api-list-container::-webkit-scrollbar {
  width: 6px;
}

.api-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.api-list-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.api-list-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

:deep(.ant-select-dropdown) {
  max-height: 300px;
}

/* 字段分组样式 */
.field-groups {
  margin-top: 16px;
}

.field-group {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.group-title {
  margin: 0 0 16px 0;
  color: #1890ff;
  font-size: 16px;
  font-weight: bold;
  padding-bottom: 8px;
  border-bottom: 2px solid #1890ff;
}

.field-group .ant-table {
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
}

.field-group .ant-table-thead > tr > th {
  background: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.field-group .ant-table-tbody > tr:hover > td {
  background: #f6ffed;
}
</style>